import { CanActivate, ExecutionContext, Inject } from '@nestjs/common'
import { FastifyRequest } from 'fastify'
import { AUTH_OPTIONS } from '../auth.constants'
import { AuthModuleOptions } from '../interfaces/auth-options.interface'
import { APP_GUARD, Reflector } from '@nestjs/core'
import { RPC_ENABLED } from '@boticord/auth'

export class RpcGuard implements CanActivate {
  constructor(
    @Inject(AUTH_OPTIONS) private readonly options: AuthModuleOptions,
    private readonly reflector: Reflector,
  ) {
  }


  async canActivate(context: ExecutionContext): Promise<boolean> {
    if (context.getType() !== 'http') {
      return true
    }
    const handlers = [ context.getHandler(), context.getClass() ]
    const data = this.reflector.getAllAndOverride(RPC_ENABLED, handlers)
    if (data !== true) {
      return true
    }

    const request = context.switchToHttp().getRequest<FastifyRequest>()
    const token = request.headers['x-boticord-rpc']
    return this.options.rpcSecret === token
  }
}

export const rpcProvider = { useClass: RpcGuard, provide: APP_GUARD }